package com.khshop.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.khshop.mapper.CartMapper;
import com.khshop.pojo.Cart;
import com.khshop.service.CartService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.khshop.vo.ServiceResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 购物车 服务实现类
 * </p>
 *
 * @author zhaoyang
 * @since 2020-10-16
 */
@Service
public class CartServiceImpl extends ServiceImpl<CartMapper, Cart> implements CartService {


    @Autowired(required = false)
    CartMapper cartMapper;

    //新增购物车
    public ServiceResult<Cart> addCart(Cart cart){
        return ServiceResult.of(cartMapper.insert(cart)>0);

    }

    //修改购物车
    public ServiceResult<Cart> updateCart(Cart cart){
        return ServiceResult.of(cartMapper.updateById(cart)>0);

    }

    //删除购物车
    public ServiceResult<Cart> delCart(Integer id){
        return ServiceResult.of(cartMapper.deleteById(id)>0);

    }

    //查询购物车
    public ServiceResult<IPage<Cart>> searchCart(Map<String,String> map, Integer page, Integer limit){
        QueryWrapper<Cart> queryWrapper = new QueryWrapper<>();
        queryWrapper.allEq(map);
        Page<Cart> iPage = new Page<Cart>(page, limit);
        IPage<Cart> orderIPage = cartMapper.selectPage(iPage, queryWrapper);
        return ServiceResult.of(orderIPage,orderIPage.getSize()>0);

    }

    //去结算
    public ServiceResult<List<Cart>> toOrders(Integer []id){
        QueryWrapper<Cart> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("id", Arrays.asList(id));
        List<Cart> carts = cartMapper.selectList(queryWrapper);
        return ServiceResult.of(carts,carts.size()>0);
    }

    //清空购物车
    public ServiceResult<Cart> clearCart(Integer userid){
        QueryWrapper<Cart> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userid",userid);
        return ServiceResult.of(cartMapper.delete(queryWrapper)>0);
    }
}
